//
//  HJUIAlertController.m
//  KaiChat
//
//  Created by lx on 2023/10/18.
//

#import "HJUIAlertController.h"
#import "HJTableViewCell.h"
#import "HJTableView.h"

#define SectionHeaderH 8

@interface HJUIAlertAction ()

@property (nonatomic, assign) HJUIAlertActionStyle style;
@property (nonatomic, copy) void (^__nullable handler)(HJUIAlertAction *action);
 

@end

@implementation HJUIAlertAction
 
+ (instancetype)actionWithTitle:(nullable NSString *)title style:(HJUIAlertActionStyle)style handler:(void (^ __nullable)(HJUIAlertAction *action))handler {
    
    HJUIAlertAction *alertAction = [[HJUIAlertAction alloc] init];
    alertAction ->_title = title;
    alertAction.style = style;
    alertAction.handler = handler;
    return alertAction;
}

@end

@interface HJUIAlertActionCell: HJTableViewCell
 

@property (nonatomic, strong) HJUIAlertAction *action;
@property (nonatomic, weak) UILabel *titleLabel;
@property (nonatomic, weak) UIView *lineView;

@end

@implementation HJUIAlertActionCell
 
 
- (void)settingSubView {
    
    self.backgroundColor = UIColor.whiteColor;
    
    UILabel *titleLabel = [UILabel lableWithSuperView:self.contentView font:UIFontMake(16) color:UIColor.tj_333333Color title:nil textAlignment:NSTextAlignmentLeft];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.offset(0);
    }];
        
    UIView *lineView = [UIView addToView:self.contentView];
    lineView.backgroundColor = UIColor.tj_separatorColor;
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.offset(lineHeight);
    }];
    
    _titleLabel = titleLabel;
    _lineView = lineView;
}

- (void)setAction:(HJUIAlertAction *)action {
    _action = action;
    
    _titleLabel.text = action.title;
    _lineView.hidden = NO;
    
    if (_action.style == HJUIAlertActionStyleDefault) {
        _titleLabel.textColor = UIColor.tj_333333Color;
        return;
    }
    
    if (_action.style == HJUIAlertActionStyleCancel) {
        _titleLabel.textColor = UIColor.tj_333333Color;
        _lineView.hidden = YES;
        return;
    }
    
    if (_action.style == HJUIAlertActionStyleDestructive) {
        _titleLabel.textColor = UIColor.tj_FF5100Color;
        return;
    }
    
}
 

@end



@interface HJUIAlertController ()<UITableViewDataSource, UITableViewDelegate, UIGestureRecognizerDelegate>

@property (nonatomic, copy) NSString *message;
@property (nonatomic, assign) HJUIAlertControllerStyle preferredStyle;
@property (nonatomic, strong) NSMutableArray <NSMutableArray *>*actionArray;

@property (nonatomic, weak) UIView *maskView;
@property (nonatomic, weak) UIView *mainContentView;
@property (nonatomic, strong) HJTableView *tableView;

@property (nonatomic, assign) bool hasCancel;

@end

@implementation HJUIAlertController

static NSString *const alertActionCell = @"alertActionCell";


+ (instancetype)alertControllerWithTitle:(nullable NSString *)title message:(nullable NSString *)message preferredStyle:(HJUIAlertControllerStyle)preferredStyle {
    
    HJUIAlertController *alertController = [[HJUIAlertController alloc] init];
    alertController.title = title;
    alertController.message = message;
    alertController.preferredStyle = preferredStyle;
    return alertController;
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        self.modalPresentationStyle = UIModalPresentationCustom;
    }
    return self;
}

- (void)showInViewController:(UIViewController *)viewController {
    [viewController presentViewController:self animated:NO completion:nil];
}


- (void)addAction:(HJUIAlertAction *)action {
    if (!action) return;
    if (action.style == HJUIAlertActionStyleCancel) {
        [self.actionArray.lastObject addObject:action];
    } else {
        [self.actionArray.firstObject addObject:action];
    }
}

- (NSArray<NSArray <HJUIAlertAction *> *> *)actions {
    return self.actionArray;
}

- (NSMutableArray *)actionArray {
    if (!_actionArray) {
        _actionArray = [NSMutableArray array];
        [_actionArray addObject:@[].mutableCopy];
        [_actionArray addObject:@[].mutableCopy];
    }
    return _actionArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
}

- (void)setupUI {
    
    self.view.backgroundColor = UIColor.clearColor;
    
    UIView *maskView = [UIView addToView:self.view];
    maskView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0];
    maskView.frame = self.view.bounds;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapMaskView)];
    [maskView addGestureRecognizer:tap];
    tap.delegate = self;
    
    UIView *mainContentView = [[UIView alloc] initWithFrame: CGRectMake(0, KScreenHeight, KScreenWidth, 307)];
    mainContentView.backgroundColor = UIColor.whiteColor;
    [maskView addSubview:mainContentView];
    self.tableView.rowHeight = 50;
    [mainContentView addSubview:self.tableView];
    
    CGFloat addH = 0;
    
    if (!isEmptyString(self.title)) {
        
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 60)];
        headerView.backgroundColor = UIColor.whiteColor;
        
        self.tableView.tableHeaderView = headerView;
        UILabel *titleLabel = [UILabel lableWithSuperView:headerView font:UIFontMake(14) color:UIColor.tj_868391Color title:self.title textAlignment:NSTextAlignmentLeft];
        [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.offset(0);
        }];
            
        addH = headerView.tj_height;
        
        UIView *lineView = [UIView addToView:headerView];
        lineView.backgroundColor = UIColor.tj_separatorColor;
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.offset(0);
            make.height.offset(lineHeight);
        }];
    }
    
    mainContentView.tj_height = self.tableView.rowHeight * ( self.actionArray.firstObject.count + self.actionArray.lastObject.count) + addH + TabbarSafeBottomMargin + (self.actionArray.lastObject.count > 0 ? SectionHeaderH : 0);
    
    self.tableView.scrollEnabled = NO;
    self.tableView.bounces = NO;
    self.tableView.backgroundColor = UIColor.whiteColor;
    [self.tableView registerClass:HJUIAlertActionCell.self forCellReuseIdentifier:alertActionCell];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);
        make.left.right.offset(0);
        make.bottom.offset(-TabbarSafeBottomMargin);
    }];
    
    
    UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:mainContentView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(10, 10)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = mainContentView.bounds;
    maskLayer.path = bezierPath.CGPath;
    mainContentView.layer.mask = maskLayer;

    _maskView = maskView;
    _mainContentView = mainContentView;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
}
 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.actionArray.lastObject.count) return self.actionArray.count;
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.actionArray[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HJUIAlertActionCell *cell = [tableView dequeueReusableCellWithIdentifier:alertActionCell forIndexPath:indexPath];
    HJUIAlertAction *alertAction = self.actionArray[indexPath.section][indexPath.row];
    cell.action = alertAction;
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(HJUIAlertActionCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger numberOfRows = [tableView numberOfRowsInSection:indexPath.section];

    if (indexPath.row == 0 && numberOfRows == 1) {
        cell.lineView.hidden = YES;
    } else  if (indexPath.row == 0) {
        cell.lineView.hidden = NO;
    } else if (indexPath.row == numberOfRows - 1) {
        cell.lineView.hidden = YES;
    } else {
        cell.lineView.hidden = NO;
    }

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    HJUIAlertAction *alertAction = self.actionArray[indexPath.section][indexPath.row];
    [self dismissComplete:^{
        if (alertAction.handler) {
            alertAction.handler(alertAction);
        }
    }];
}


- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
   if (section == 0) return SectionHeaderH;
   return 0.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (self.actionArray.lastObject.count) {
        UIView *view = [[UIView alloc] init];
        return view;
        
    };
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] init];
    if (section == 0) {
        view.backgroundColor = UIColor.tj_F3F2F7Color;
    } else {
        view.backgroundColor = UIColor.tj_F3F2F7Color;
    }

    return view;
}

- (HJTableView *)tableView{
    if (!_tableView) {
        HJTableView *tableView = [[HJTableView alloc] init];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.rowHeight = 55;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.backgroundColor = [UIColor whiteColor];
        _tableView = tableView;
    }
    return _tableView;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return (touch.view == self.maskView);
}

- (void)tapMaskView {
    HJUIAlertAction *alertAction = [self.actionArray.lastObject lastObject];
    [self dismissComplete:^{
        if (alertAction.handler) {
            alertAction.handler(alertAction);
        }
    }];
}

- (void)dismissComplete:(void (^)(void))complete {
    
    [UIView animateWithDuration:0.25 animations:^{
        self.maskView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0];
        self.mainContentView.tj_y = KScreenHeight;
    } completion:^(BOOL finished) {
        [self dismissViewControllerAnimated:NO completion:^{
            if (complete) {
                complete();
            }
        }];
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
 
    [UIView animateWithDuration:0.35 delay:0 usingSpringWithDamping:0.95 initialSpringVelocity:0.8 options:UIViewAnimationOptionCurveEaseIn animations:^{
        self.mainContentView.tj_y = KScreenHeight - self.mainContentView.bounds.size.height;
        self.maskView.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.35];
    } completion:nil];
}

 

@end
